// packageF/sachertorte/sachertorteIndex/sachertorteIndex.js
let app = getApp();
let location = require("../../../mybehaviors/location/location");
const skinBehavior = require('../../../utils/themeSkin/skinBehavior');
Page({
  behaviors: [location,skinBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    banner: [], //轮播图
    notice: "",  //公告
    category: [], //分类
    goods: [], //抢购列表
    brand: [], //品牌
    advertising: {},
    recommandList:[],
    purchaseTime: 0,
    Hei:"",          //这是swiper要动态设置的高度属性
    page:1,
    totalPage:0,
    isLoadMore: true,
    cakeCity:'',
    point:{},
    imgPath: app.globalData.imgPath,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.city) {
      this.setData({
        cakeCity:(options.city).trim()
      })
    }
    this.goodsByRecommand();
    this.frontendIndex();
  },
  imgH(e){
    var winWid = wx.getSystemInfoSync().windowWidth;//获取当前屏幕的宽度
    var imgh=e.detail.height;//图片高度
    var imgw=e.detail.width;
    var swiperH=winWid*imgh/imgw + "px"　//等比设置swiper的高度。  即 屏幕宽度 / swiper高度 = 图片宽度 / 图片高度    ==》swiper高度 = 屏幕宽度 * 图片高度 / 图片宽度
    this.setData({
        Hei:swiperH//设置高度
    })
  },
  addressTo() {
    wx.navigateTo({
      // url:'/packageC/o2o/o2oLocation/o2oLocation?tag=cake'
      url: '/packageI/citypickerPage/citypickerPage?plu=cake'
    })
  },
  swiperNav(event) {
    let nav = event.target.dataset.url;
    wx.navigateTo({
      url:nav
    })
  },
  handpickNav(event) {
    let id = event.currentTarget.dataset.id;
    wx.navigateTo({
      url:`/packageF/sachertorte/classify/classify?brandId=${id}&city=${this.data.cakeCity}` 
    })
  },
  classifyNav(event) {
    let id = event.currentTarget.dataset.item.id || '';
    let name = event.currentTarget.dataset.item.name;
    if(name == '品牌馆'){
      wx.navigateTo({
        url: '/packageF/sachertorte/sachertorteBand/sachertorteBand?city='+this.data.cakeCity,
      })
      return
    }
    wx.navigateTo({
      url:`/packageF/sachertorte/classify/classify?id=${id}&classifyName=${name}&city=${this.data.cakeCity}` 
    })
  },
  searchNav() {
    wx.navigateTo({
      url:`/packageF/sachertorte/sachertorteSearch/sachertorteSearch?city=${this.data.cakeCity}`
    })
  },
  purchaseOn() {
    wx.navigateTo({
      url:`/packageF/sachertorte/purchase/purchase?city=${this.data.cakeCity}`
    })
  },
  goodsNav(event) {
    let id = event.currentTarget.dataset.id || '';
    wx.navigateTo({
      url:`/packageF/sachertorte/sachertorteGoods/sachertorteGoods?id=${id}&city=${this.data.cakeCity}`
    })
  },
  adverNav(event) {
    let nav = event.target.dataset.url;
    wx.navigateTo({
      url:nav
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    try {
      this._getLocation((mapdata, e) => { //获取定位的城市，拿到定位的信息
        let city = mapdata.address_component.city || '';
        if(!this.data.cakeCity) {
          this.setData({
            cakeCity:city,
          });
        }
        this.setData({
          point:{
            lng:e.lng,
            lat:e.lat
          }
        })
        //定位后调用首页接口和推荐列表接口
        this.goodsByRecommand();
        this.frontendIndex();
      });
    } catch (e) {
      console.log(e);
      this.goodsByRecommand();
      this.frontendIndex();
    }
  },
  toBand(e){
    let id = e.currentTarget.dataset.item.id;
    wx.navigateTo({
      url: `/packageF/sachertorte/sachertorteBandShop/sachertorteBandShop?brand_id=${id}&city=${this.data.cakeCity}`,
    })
  },
  frontendIndex() {
    let query = {
      city:this.data.cakeCity,
    };
    let urlStr = app.getNetAddresss("plugin.yz-supply-cake.frontend.index.index");
    app._getNetWork({
      url: urlStr,
      data:query,
      success: (resdata) => {
        let res = resdata.data
        if (res.result == 1) {
          let goods = res.data.goods;
          let date = new Date((res.data.goods[0]?.promotion_end_at)?.replace(/-/g,'/'));
          let timeDate = date.getTime();
          let current = new Date().getTime();
          this.setData({
            advertising: res.data.advertising,
            goods: res.data.goods,
            category: res.data.category,
            banner: res.data.banner,
            brand: res.data.brand,
            notice: res.data.notice,
            purchaseTime: timeDate - current
          })
          let advc = [{ name: '品牌馆', thumb_url: `${this.data.imgPath}images%2Fsachertorte%2Fband%402x.png` }]
          this.setData({
            category:[...this.data.category, ...advc]
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  goodsByRecommand() {
    let query = {
      page:this.data.page,
      city: this.data.cakeCity,
      lng: this.data.point.lng ? this.data.point.lng : '',
      lat: this.data.point.lat ? this.data.point.lat : '',
      pageSize: 5,
      is_recommend :1
    }
    let urlStr = app.getNetAddresss("plugin.yz-supply-cake.frontend.goods.goods.getBrandAndGoodsAndStore");
    app._postNetWork({
      url: urlStr,
      data:query,
      success:  (resdata) => {
        let res = resdata.data;
        wx.hideLoading();
        wx.hideNavigationBarLoading();//隐藏导航条加载动画
        //停止下拉刷新
        wx.stopPullDownRefresh();
        if (res.result == 1) {
          this.data.totalPage = res.data.last_page;
          if (!this.data.totalPage) {
            this.data.totalPage = 0;
          }
          this.data.isLoadMore = true;
          this.setData({
            recommandList: res.data.data,
          })
        } else {
          this.data.page = this.data.page - 1;
          this.isLoadMore = false;
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  //获取更多数据
  getMoreData() {
    this.data.isLoadMore = false; // 防止多次请求分页数据
    if (this.data.page >= this.data.totalPage) {
      return;
    } else {
      this.data.page = this.data.page + 1;
      let query = {
        page:this.data.page,
        city: this.data.cakeCity,
        lng: this.data.point.lng ? this.data.point.lng : '',
        lat: this.data.point.lat ? this.data.point.lat : '',
        pageSize: 10,
        is_recommend :1
      }
      let urlStr = app.getNetAddresss("plugin.yz-supply-cake.frontend.goods.goods.getBrandAndGoodsAndStore");
      app._getNetWork({
        url: urlStr,
        data: query,
        success: (resdata) => {
          let res = resdata.data;
          let list = res.data.data;
          if (res.result == 1) {
            this.data.isLoadMore = true;
            this.setData({
              recommandList : this.data.recommandList.concat(list),
            })
          } else {
            this.data.query.page = this.data.query.page - 1;
            this.data.isLoadMore = false;
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isLoadMore) {
      this.getMoreData();
    } else {
      console.log('没有更多了');
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})